<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends BaseModel
{
    use HasFactory;
    protected $table = 'product';
    // 允许批量操作的字段
    protected $fillable = ['product_name','sort','sort_info','is_del','modelid','created_at','updated_at'];

    public function scopeSearch($query,$params)
    {
        if(!empty($params['product_name'])){
            $query->where('product_name','like','%'.$params['product_name'].'%');
        }

        if(!empty($params['color_id'])){
            $product_id_arr = ProductColor::where('color_id',$params['color_id'])->pluck('product_id')->toArray();
            $query->whereIn('id',$product_id_arr);
        }



        $query->where('is_del',$params['is_del']??2);

        if(isset($params['field_list']) && !empty($params['field_list'])){
            $select_arr = explode(',',$params['field_list']);
        }else{
            $select_arr = "*";
        }
        $query->select($select_arr);
        return $query;
    }

    /**
     * 多对多
     * 被关联的模型 , 多对多模型的关系表名 , 中间表与当前模型关联的字段名 , 中间表与被关联模型关联的字段名);
     */
    //产品颜色
    public function color(){
        return $this->belongsToMany(Color::class,'product_color','product_id','color_id');
    }

    //型号
    public function model_number(){
        return $this->belongsToMany(ModelNumber::class,'product_model_number','product_id','model_number_id')
            ->where('model_number.is_del',2)->with('file');
    }

    //产品工种排序
    public function job_type(){
        return $this->belongsToMany(JobType::class,'product_job_type','product_id','job_type_id');
    }

    //产品模型
    public function product_models(){
        return $this->hasOne(Models::class,'modelid','modelid');
    }





}
